package com.base.receiver

import android.content.BroadcastReceiver
import android.content.Intent
import android.text.TextUtils
import android.bluetooth.BluetoothAdapter
import android.widget.Toast
import com.base.receiver.BleStatusReceiver
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.util.Log
import com.base.event.BleEvent
import com.base.event.post.postEvent

/* IntentFilter intentFilter = new IntentFilter();
        // 监视蓝牙关闭和打开的状态
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        // 监视蓝牙设备与APP连接的状态
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);

        // 注册广播
        registerReceiver(this.bleListenerReceiver, intentFilter);
*/
class BleStatusReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent?) {
        val action = intent?.action
        if (TextUtils.isEmpty(action)) {
            return
        }
        when (action) {
            BluetoothAdapter.ACTION_STATE_CHANGED -> {
                val blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
                when (blueState) {
                    BluetoothAdapter.STATE_TURNING_ON -> {
                        showToast(context, "蓝牙正在打开")
                        Log.e(TAG, "蓝牙正在打开")
                        postEvent(BleEvent(true))
                    }
                    BluetoothAdapter.STATE_ON -> {
                        showToast(context, "蓝牙已经打开")
                        Log.e(TAG, "蓝牙已经打开")
                        postEvent(BleEvent(true))
                    }
                    BluetoothAdapter.STATE_TURNING_OFF -> {
                        showToast(context, "蓝牙正在关闭")
                        Log.e(TAG, "蓝牙正在关闭")
                        postEvent(BleEvent(false))
                    }
                    BluetoothAdapter.STATE_OFF -> {
                        showToast(context, "蓝牙已经关闭")
                        Log.e(TAG, "蓝牙已经关闭")
                        postEvent(BleEvent(false))
                    }
                }
            }
            BluetoothDevice.ACTION_ACL_CONNECTED -> {
                showToast(context, "蓝牙设备已连接")
                Log.e(TAG, "蓝牙设备已连接")
            }
            BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
                showToast(context, "蓝牙设备已断开")
                Log.e(TAG, "蓝牙设备已断开")
            }
        }
    }

    private fun showToast(context: Context, message: CharSequence) {
        //Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }

    companion object {
        private const val TAG = "BleStatusReceiver"
    }
}